package com.dragonfly.shutter.services;

import java.util.Date;

import com.dragonfly.shutter.DAOs.BrowseLogDAO;
import com.dragonfly.shutter.DAOs.PictureDAO;
import com.dragonfly.shutter.DAOs.ScoreDAO;
import com.dragonfly.shutter.beans.BrowseLog;
import com.dragonfly.shutter.beans.Score;

/**
 * 用户评分Bean
 * @author 黄挺
 *
 */
public class ScoreService {
	private BrowseLogDAO browseLogDAO;
	private ScoreDAO scoreDAO;
	private PictureDAO pictureDAO;
	
	/**
	 * 用户评分服务类
	 * @param userID 用户ID
	 * @param pictureID 评分ID
	 * @param score 评分
	 * @param requestURL 请求URL
	 */
	public void doService(Integer userID, String pictureID, Integer score,
			String requestURL) {
		BrowseLog browseLog = new BrowseLog(userID, new Date(System.currentTimeMillis()), requestURL);
		
		doDBOperate(userID, pictureID, score, browseLog);
	}
	
	/**
	 * 用户评分数据库操作函数
	 * @param userID 用户ID
	 * @param pictureID 图片ID
	 * @param score 评分
	 * @param browseLog 日志Bean
	 */
	private void doDBOperate(Integer userID, String pictureID, Integer score, BrowseLog browseLog) {
		int totalScore = 0;
		browseLogDAO.insertBrowseLog(browseLog);
		Score oldScore = scoreDAO.selectPictureScore(new Score(userID, pictureID, 0)); 
		
		if( oldScore == null){
			scoreDAO.insertScore(new Score(userID, pictureID, score));
			totalScore = score;
		}
		else{
			scoreDAO.updateScoreByScoreId(new Score(userID, pictureID, score));
			totalScore = score - oldScore.getScore();
		}
		
		int newScore = pictureDAO.selectTotalScore(pictureID);
		pictureDAO.updatePicScore(pictureID, newScore + totalScore);
	}

	public void setBrowseLogDAO(BrowseLogDAO browseLogDAO) {
		this.browseLogDAO = browseLogDAO;
	}
	
	public void setScoreDAO(ScoreDAO scoreDAO) {
		this.scoreDAO = scoreDAO;
	}

	public void setPictureDAO(PictureDAO pictureDAO) {
		this.pictureDAO = pictureDAO;
	}
}
